package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;

    @Override
    public PageResult getPageResult(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> objectPage = Page.of(page, pageSize);
        objectPage.addOrder(OrderItem.desc("update_time"));
        objectPage = lambdaQuery().like(name != null && !name.isEmpty(), Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getUpdateTime, begin, end)
                .page(objectPage);


        // 调用page方法完成分页查询


        //获取班主任集合
        List<Clazz> clazzList = objectPage.getRecords();
        //获取班主任的id
        List<Integer> collect = clazzList.stream().map(clazz -> clazz.getMasterId())
                .collect(Collectors.toList());
        if (!collect.isEmpty()) {
            List<Emp> emps = empService.listByIds(collect);
            clazzList.forEach(clazz -> {
                emps.forEach(emp -> {
                    if (clazz.getMasterId() != null && clazz.getMasterId().equals(emp.getId())) {
                        clazz.setMasterName(emp.getName());
                    }
                });
            });
        }


        // 封装结果并返回
        return new PageResult(objectPage.getTotal(), clazzList);
    }
}
